package com.mojito.gorm.session.impl;

import com.mojito.gorm.executor.GormExecutor;
import com.mojito.gorm.map.SqlMapInfo;
import com.mojito.gorm.session.GormConfiguration;
import com.mojito.gorm.session.GormSession;

import java.util.List;

/**
 * @author mojito
 */
public class DefaultGormSession implements GormSession {

    private GormConfiguration configuration;
    private GormExecutor executor;

    public DefaultGormSession(GormConfiguration configuration) {
        this.configuration = configuration;
        this.executor = configuration.newExecutor();
    }

    public GormConfiguration getConfiguration() {
        return configuration;
    }

    public GormExecutor getExecutor() {
        return executor;
    }

    @Override
    public <T> T selectOne(String statement, Object... params) {
        List<T> objects = selectList(statement, params);
        if (objects.size() <= 1) {
            return objects.get(0);
        }
        throw new RuntimeException("Too many result.Need one but more than one");
    }

    @Override
    public <E> List<E> selectList(String statement, Object... params) {
        SqlMapInfo sqlMapInfo = configuration.sqlMaps.get(statement);
        if (sqlMapInfo == null) {
            throw new RuntimeException("sqlMapInfo not found");
        }
        return executor.execute(sqlMapInfo, params);
    }

    @Override
    public <T> T getMapper(Class<?> clazz) {
        return (T) configuration.getMapper(clazz, this);
    }
}
